﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Microsoft.Azure.E2E.Common.Specialized
{
    public abstract class TypeSegregatedLookupBase<TSelf, TCommonStorage>
        where TSelf : TypeSegregatedLookupBase<TSelf, TCommonStorage>
    {
        private static readonly List<Type> Registrations = new List<Type>();

        private static readonly Dictionary<Type, TCommonStorage> RegistrationLookupByVariantType = new Dictionary<Type, TCommonStorage>();

        private static readonly object Sync = new object();

        private static class Store<T>
        {
            private static int _existsValue;

            private static TCommonStorage _value;

            public static TCommonStorage Value { get { return _value; } }

            public static bool Exists
            {
                get { return Interlocked.CompareExchange(ref _existsValue, 1, 1) == 1; }
            }

            public static bool TrySet(TCommonStorage value)
            {
                if (Interlocked.CompareExchange(ref _existsValue, 1, 0) != 0)
                {
                    return false;
                }

                lock (Sync)
                {
                    Registrations.Add(typeof(T));
                    RegistrationLookupByVariantType[typeof(T)] = _value = value;
                }

                return true;
            }
        }

        public static bool CanBeFound()
        {
            lock (Sync)
            {
                return CanBeFoundInternal();
            }
        }

        private static bool CanBeFoundInternal()
        {
            return Registrations.Count > 0;
        }

        public static TCommonStorage Find(Type data)
        {
            TCommonStorage result;

            lock (Sync)
            {
                if (!CanBeFoundInternal() || !RegistrationLookupByVariantType.TryGetValue(data, out result))
                {
                    throw new KeyNotFoundException("Could not find an entry for the specified value");
                }
            }

            return result;
        }

        public static TCommonStorage Find<TData>()
        {
            if (Store<TData>.Exists)
            {
                return Store<TData>.Value;
            }

            throw new KeyNotFoundException("Could not find an entry for the specified value");
        }

        protected static bool TrySet<TData>(TCommonStorage value)
        {
            return Store<TData>.TrySet(value);
        }
    }
}
